<template>
  <view class="container">
    <view class="index-page" :style="pageStyle">
      <uni-nav-bar
        backgroundColor="transparent"
        color="#fff"
        :border="false"
        :statusBar="true"
        fixed
        leftWidth="0"
        rightWidth="0"
        @clickLeft="$goBack"
        :custom-bg-style="{
          background: stickyFix
            ? `pink url(${VUE_APP_STATIC_URL}ui-static/zwx-static/head-bg-staging.png) no-repeat center top`
            : 'transparent',
          backgroundSize: '100% auto',
        }"
      >
        <view
          class="flex items-center navbar-center overflow"
          style="line-height: 88rpx"
        >
          <image
            :src="`${VUE_APP_STATIC_URL}ui-static/zwx-static/home/logo-staging.png`"
            style="height: 56rpx"
            mode="heightFix"
          >
          </image>
        </view>
      </uni-nav-bar>
      <view class="container flex flex-column">
        <view
          class="search"
          @click="$jump(`/zwx_category_page1/search/index/index`)"
        >
          <view class="search-text">请输入您想要的宝贝</view>
        </view>
        <u-sticky
          :offset-top="stickyOffsetTop"
          bg-color="transparent"
          z-index="999"
          @fixed="stickyFix = true"
          @unfixed="stickyFix = false"
        >
          <view
            class="tabs_box border-box"
            :style="{
              backgroundColor: 'transparent',
              backgroundImage: stickyFix
                ? `url(${VUE_APP_STATIC_URL}ui-static/zwx-static/head-bg-test.jpg)`
                : 'none',
              backgroundPosition: `center -${navBarHeight}px`,
            }"
          >
            <view style="height: 1rpx"></view>
            <u-tabs
              :list="categoryList"
              v-model="tabsCurrent"
              @change="tabsChange"
              active-color="#fff"
              inactive-color="#fff"
              :active-item-style="{ fontSize: '36rpx' }"
              font-size="30rpx"
              :bar-style="tabsBarStyle"
              :gutter="20"
              bg-color="transparent"
              :bar-width="35"
              :bar-height="14"
              scroll-bar="false"
            ></u-tabs>
          </view>
        </u-sticky>
        <TemplatePage
            ref="templatePageRef"
          v-if="tabsCurrent === 0"
        />
        <view class="category-box" v-if="tabsCurrent !== 0">
          <HomeProList
              ref="homeProListRef"
              :categoryid="categoryid"
          />
        </view>

      </view>
    </view>

    <!-- 弹窗广告 -->
    <ad-window ref="adWindowRef" :triggerCondition="1"></ad-window>
    <tui-modal :show="privacyShow" :custom="true" :fadein="true">
      <view class="Put-box1">
        <view class="text-align fs34 fs-bold"> 协议与隐私政策 </view>
        <p class="mar-top-20">
          欢迎来到zkmall！我们根据最新的法律、法规、监管政策要求，更新了zkmall隐私政策。
        </p>
        <view class="flex-display flex-sp-between">
          <view class="btn submit" @click="privacyShow = false"> 同意 </view>
        </view>
      </view>
    </tui-modal>

    <!-- 回到顶部 -->
    <ReturnTop :returnTopFlag="returnTopFlag" />
  </view>
</template>

<script lang="ts" setup>
import { computed, ref, inject, nextTick, toRefs, onMounted } from "vue";
import tuiModal from "@/components/modal/modal.vue";
import AdWindow from "@/components/adWindow.vue";
import { request } from "@/utils/request";
import { onLoad, onReachBottom, onPageScroll } from "@dcloudio/uni-app";
import TemplatePage from "@/components/template/index.vue";
import HomeProList from "@/components/basics/homeProList.vue";
import { useStore } from "vuex";
import _ from "lodash";
import { VUE_APP_STATIC_URL } from "@/config/api";
import API from "@/config/api";
const store = useStore();
const $goBack = inject("$goBack");
const $jump = inject("$jump");

const loading = ref(false);
const canvasData = ref<{ type?: number }>({});
const returnTopFlag = ref(false); // 返回顶部显示隐藏

const adWindowRef = ref();
const privacyShow = ref(false);

onLoad(() => {
  if (!uni.getStorageSync("storage_key")) {
    // #ifdef APP-PLUS
    privacyShow.value = true;
    // #endif
  }
  nextTick(() => {
    adWindowRef.value.getAd();
  });
});

const navBarHeight = computed(
  () => store.state.globalSetting.appSetting.navBarHeight
);
const tabBarHeight = computed(
  () => store.state.globalSetting.appSetting.tabBarHeight
);

const pageStyle = computed(() => ({
  paddingBottom: `${tabBarHeight.value}px`,
}));

const stickyFix = ref(false);
// #ifndef H5
let { osName, statusBarHeight, deviceModel } = uni.getSystemInfoSync();

let top_val = 0;

if (osName == "ios") {
  if (deviceModel === "iPhone 6/7/8 Plus") {
    top_val = 4;
  } else if (deviceModel === "iPhone XR") {
    top_val = 8;
  } else if (_.map(deviceModel.match(/\d+/g), Number)[0] >= 12) {
    if (deviceModel.includes("Pro") || deviceModel.includes("Max")) {
      top_val = 16;
    } else {
      top_val = 8;
    }
  } else {
    top_val = 0;
  }
} else {
  top_val = statusBarHeight;
}

var stickyOffsetTop = ref(navBarHeight.value * 2 - top_val);
// #endif

// #ifdef H5
var stickyOffsetTop = ref(0);
// #endif
const categoryGroupRef = ref()
const categoryList = ref([]);
const tabsCurrent = ref(0);
const categoryid = ref(0);
const tabsChange = (index) => {
  categoryid.value = categoryList.value[index].id;
  HandleCleanActiveTabProduct();
  // nextTick(() => {
  //   if(categoryGroupRef.value){
  //     categoryGroupRef.value.getCategoryData()
  //   }
  // })
  uni.pageScrollTo({
    scrollTop: 0,
  });
};

/**
 * 清空非首页的子组件商品数据
 * 回滚请求参数到起始页
 * */
const homeProListRef = ref();
function HandleCleanActiveTabProduct() {
  nextTick(() => {
    if (homeProListRef.value) {
      let pitchOnPage = homeProListRef.value;
      pitchOnPage.total = 0;
      pitchOnPage.page = 1;
      pitchOnPage.productList = [{}, {}, {}, {}, {}, {}, {}, {}];
      pitchOnPage.getData(1);
    }
  });
}

/**
 * 请求非首页的子组件的下一页
 * */
const templatePageRef = ref(null)
function HandleLoadMoreProduct() {
  if (tabsCurrent.value != 0) {
    let pitchOnPage = homeProListRef.value;
    if (
      pitchOnPage.total !== 0 &&
      pitchOnPage.productList.length < pitchOnPage.total
    ) {
      pitchOnPage.page++;
      pitchOnPage.getData();
    }
  } else {
      templatePageRef.value.load()
    // 首页画布
    // const lastComponent = componentsData.value.at(-1)
    // if (lastComponent && lastComponent.type === 'productList' && lastComponent.componentContent.openBottomLoad) {
    //   console.log('商品组件触底加载', canvasPageRef.value)
    //   canvasPageRef.value && canvasPageRef.value.loadMore()
    // }

  }
}

// 由于u-tabs封装不完美，这里的属性不能使用驼峰式代替
const tabsBarStyle = {
  "background-image": `url(${VUE_APP_STATIC_URL}ui-static/zwx-static/home/sort-Markers-white.png)`,
  "background-repeat": "no-repeat",
  "background-position": "center center",
  "background-size": "100% auto",
  "border-radius": 0,
  "background-color": "transparent",
  bottom: "-14rpx",
};

// 获取分类数据
function getCategoryData() {
  // uni.showLoading({
  //   title:'加载中...'
  // })
  request(API.FindCategoryListByDepth, {}, "GET")
    .then((res) => {
      categoryList.value = res.data.map((v) => {
        return {
          name: v.classifyName,
          id: v.classifyId,
        };
      });
      categoryList.value.unshift({
        name: "首页",
        id: 0,
      });
      console.log(categoryList.value, "categoryList.value");
      // uni.hideLoading()
    })
    .catch((err) => {
      // uni.hideLoading()
      throw Error(err);
    });
}

onMounted(() => {
  getCategoryData();
});

onReachBottom(() => {
  HandleLoadMoreProduct();
});

onPageScroll(e => {
  returnTopFlag.value = e.scrollTop > 600;
});
</script>

<style lang="scss" scoped>
@import "../../../style/images";
.index-page {
  min-height: 100vh;
  height: 100%;
  overflow-y: auto;
  background-color: #f5f3f1;
  background-image: url('#{$base-path}ui-static/zwx-static/head-bg-staging.png');
  background-size: 100%;
  background-repeat: no-repeat;
  /* #ifdef H5 */
  background-position: center -55rpx;
  /* #endif */
  .canvas-page {
    padding-top: 40rpx;
  }
}

.container {
  .search_box {
    // width: 100%;
    // padding: 0 30rpx;
    width: 690rpx;
    margin: 0 30rpx;
    border: 2px solid transparent;
    border-radius: 32rpx;
  }

  .tabs_box {
    width: 100%;
    padding: 0 30rpx;
    background-size: 100% auto;
    background-repeat: no-repeat;
  }

  .search {
    margin: 0 30rpx;
    height: 64rpx;
    border-radius: 32rpx;
    line-height: 64rpx;
    padding-left: 68rpx;
    font-size: 20rpx;
    color: #9f9f9f;
    background: #ffffff
      url("#{$base-path}ui-static/zwx-static/home/search-icon.png")
      no-repeat 18rpx center / 36rpx 34rpx;
  }
}
</style>
